package com.asset.dispoal.abolishPool.service.common;

import com.asset.dispoal.abolishPool.domain.db.entity.GbAbolishCaseContent;
import com.asset.dispoal.abolishPool.domain.db.mapper.AbolishCaseContentMapper;
import com.asset.dispoal.abolishPool.dto.SaveAbolishPoolRequest;
import com.asset.dispoal.abolishPool.service.converter.AbolishConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

/**
 * @description:
 * @author: yf
 * @date: 2022-09-22 14:21:07
 */
@Repository
public class SaveAbolishPoolCommand implements BaseCommand<SaveAbolishPoolRequest, Result> {

    @Autowired
    private AbolishCaseContentMapper abolishCaseContentMapper;

    @Autowired
    private BaseIdeable<String> snowFlake;

    @Override
    public Result execute(SaveAbolishPoolRequest request) {
        GbAbolishCaseContent caseContent = AbolishConverter.INSTANCE.reqToDo(request);
        if (StringUtil.isBlank(request.getId())) {
            //新增
            caseContent.setId(snowFlake.generateId());
            caseContent.setState("1");
        }
        //判断新值是否默认是否有值 有值则将数据库默认值修改为 0
        long count = abolishCaseContentMapper.count(GbAbolishCaseContent.builder()
                .useDefault("1")
                .state("1")
                .build());
        if (count == 1) {
            //判断当前修改值是否为默认值
            long nums = abolishCaseContentMapper.count(GbAbolishCaseContent.builder()
                    .id(caseContent.getId())
                    .useDefault("1")
                    .state("1")
                    .build());
            if ((nums > 0) && ("0".equals(caseContent.getUseDefault()))) {
                return Result.faild("当前值已经为默认值！请检查");
            }
        }
        if (count <= 0) {
            caseContent.setUseDefault("1");
        } else {
            if (caseContent.getUseDefault().equals("1")) {
                abolishCaseContentMapper.updateDefaultState();
                caseContent.setUseDefault("1");
            }
        }
        int update = abolishCaseContentMapper.insertOrUpdate(caseContent);
        return update <= 0 ? Result.faild("数据保存失败！") : Result.ok();
    }
}
